const App = getApp()
import {
	url
} from '../../../../modelApi/url_config.js'
var setTimeoutObj = '';
Page({
	data: {
		scrollTop: 0,
		statusBarPadding: "",
		inputModalVisible: false, // 显示聊天框
		videoStatus: true, // vedio视频播放状态 true,播放  false 暂停
		playBtnVisible: false, //显示播放，暂停的图标
		showShareBool: false,
		clickShowShops: false, //是否显示弹窗内容
		showShopsOpen: false, //显示弹窗或关闭弹窗的操作动画
		roomInfo: {}, // 直播房间详情
		roomId: "", //房间id
		streamInfo: {}, // 直播拉流详情
		shopParams: {
			"pageNo": 1,
			"pageSize": 50
		}, //商品列表参数
		goodsList: [], //商品列表
		IMmsgList: [],
		textTalk: '',
		inputshowFlag: false,
		inptxt: '跟主播聊点什么...',
		isFocus: '', //是否已关注
		maskHidden: false,
		qrcodeImg: '',
		conmeinList: '',
		isshowCome: '',
		count: 0,
		linshifang: false,
		memberNum: 0,
	},
	onLoad(options) {
		if (!App.globalData.isShow) {
			console.log(!App.globalData.isShow)
			wx.redirectTo({
				url: "/pages/errorPage/index"
			});
			return
		}
		this.setData({
			linshifang: true
		})
		wx.hideShareMenu();
		let userid = '',
			roomid = '',
			sceneFlag = false;
		if (options.scene) {
				const scene = decodeURIComponent(options.scene)
				userid = scene.split('&')[0]
				roomid = scene.split('&')[1]
				sceneFlag = true
    } else {
				userid = options.shareUserId || ''
				roomid = options.id
		}
		userid && wx.setStorageSync('shareUserId', userid);
		if (!wx.getStorageSync("tel")) {
			let UrlData = `/pages/live/sonpages/player/player?shareUserId=${options.shareUserId}&id=${options.id}`;
			wx.setStorageSync("backPage", UrlData);
			wx.redirectTo({
				url: "/pages/register/index"
			});
			return
		};
		(options.shareUserId || sceneFlag)  && App.getimLoad(() => {
			this.addground()
		});
		this.setData({
			statusBarPadding: App.globalData.navTop,
			roomId: roomid
		});
		this.getLiveInfo(roomid);
		this.loadGoods();
	},
	onShow() {
		if (!wx.getStorageSync("tel")) {
			return
		}
		this.ImListen()
		this.getQrcode()
	},
	onHide() {
		App.globalData.wxTIM.off(App.globalData.TIM.EVENT.MESSAGE_RECEIVED, this.listenFucnback)
	},
	onUnload() {
		let promise = App.globalData.wxTIM.quitGroup(this.data.roomId);
		promise.then(function (imResponse) {
			console.log(imResponse.data.groupID, '退出成功的群 ID'); // 退出成功的群 ID
		}).catch(function (imError) {
			console.warn('quitGroup error:', imError); // 退出群组失败的相关信息
		});
	},
	clickHandler: function() {
	  this.setData({
		count: this.data.count + 1
	  });
	},
	listenFucnback(res) {
		console.log(res, "？？？？？？？？？？？？消息通知11")
		this.setData({
			isshowCome: false
		})
		const list = [];
		const conmeinList = [];
		let isshowCome = false
		res.data.map(el => {
			// 群聊天
			if (el.from !== '@TIM#SYSTEM' && el.to === this.data.roomId && el.payload.text) {
				list.push(el)
			}
			// 进群消息通知
			if (el.payload.data &&  el.payload.data === 'comeinground' && el.to === this.data.roomId) {
				this.getMember()
				conmeinList.push(el)
				isshowCome= true
			}
		})
		this.setData({
			IMmsgList: [...this.data.IMmsgList, ...list],
			conmeinList: conmeinList,
			isshowCome: isshowCome
		})
		setTimeout(()=> {
			this.setData({
				isshowCome: false
			})
		},2500)
		this.goToBottom()
	},
	getMember() {
		let promise = App.globalData.wxTIM.getGroupProfile({ groupID: this.data.roomId});
			promise.then((imResponse) => {
				console.log(imResponse.data.group.memberNum,'在线人数获取');
				this.setData({
					memberNum: imResponse.data.group.memberNum || 100
				})
			}).catch((imError) =>{
				console.warn('getGroupProfile error:', imError); // 获取群详细资料失败的相关信息
			});
	},
	addground() {
		let promise = App.globalData.wxTIM.joinGroup({
			groupID: this.data.roomId,
			type: App.globalData.TIM.TYPES.GRP_CHATROOM
		});
		promise.then((imResponse) => {
			console.log(imResponse, '加入群组')
			this.getMember()
			this.addpoint()
		}).catch(function (imError) {
			console.warn('joinGroup error:', imError);
		});
	},
	ImListen() {
		App.globalData.wxTIM.on(App.globalData.TIM.EVENT.MESSAGE_RECEIVED, this.listenFucnback)
		this.addground()
	},
	// 点赞
	addpoint() {
		let message = App.globalData.wxTIM.createCustomMessage({
			to: this.data.roomId,
			conversationType: App.globalData.TIM.TYPES.CONV_GROUP,
			payload: {
				data: 'comeinground',
				description: '',
				extension: ''
			}
		});
		// 3. 发送消息
		let promise = App.globalData.wxTIM.sendMessage(message);
		promise.then(function (imResponse) {
			// 发送成功
			console.log(imResponse,'自定义消息');
		}).catch(function (imError) {
			// 发送失败
			console.warn('sendMessage error:', imError);
		});
	},
	// 容器滚动到底部
	goToBottom() {
		const query = wx.createSelectorQuery().in(this);
		query.select('.messages-list').boundingClientRect();
		query.select('.msgList').boundingClientRect();
		query.exec(res => {
			const scorllHeight = res[0].height;
			const listHeight = res[1].height;

			this.setData({
				scrollTop: listHeight - scorllHeight
			});
		});
	},
	getOtherTial(el) {
		let promise = App.globalData.wxTIM.getUserProfile({
			userIDList: [el.from]
		});
		promise.then(function (imResponse) {
			el.nick = imResponse.data.nick
		})
	},
	bindfocus() {
		this.setData({
			inputshowFlag: true,
		})
	},
	bindblur() {
		this.setData({
			inputshowFlag: false,
		})
	},
	bindinput(e) {
		this.setData({
			textTalk: e.detail.value,
		})
	},
	bindconfirm(e) {
		let message = App.globalData.wxTIM.createTextMessage({
			to: this.data.roomId, //聊天室id
			conversationType: App.globalData.TIM.TYPES.CONV_GROUP, // 消息类型
			payload: {
				text: this.data.textTalk
			}
		});
		this.setData({
			textTalk: ''
		})
		// 2. 发送消息
		let promise = App.globalData.wxTIM.sendMessage(message);
		promise.then((res) => {
			console.log('// 发送成功', res);
			this.getownTail(res.data.message)
		}).catch((imError) => {
			console.warn('sendMessage error:', imError);
		});
	},
	// 获取IM个人资料
	getownTail(data) {
		const arr = [];
		let promise1 = App.globalData.wxTIM.getMyProfile();
		promise1.then((imResponse) => {
			console.log(imResponse.data, '个人资料 - Profile 实例'); // 个人资料 - Profile 实例
			data.nick = imResponse.data.nick
			arr.push(data)
			this.setData({
				IMmsgList: [...this.data.IMmsgList, ...arr]
			})
			this.goToBottom()
		}).catch((imError) => {
			console.warn('getMyProfile error:', imError); // 获取个人资料失败的相关信息
		});
	},
	statechange(e) {
		console.log('live-player code:', e.detail.code)
	},
	error(e) {
		console.error('live-player error:', e.detail.errMsg)
	},
	/* 播放暂停切换 */
	TogglePlayBtnVisible() {
		this.togglePlayBtnFun();
	},
	/* 播放暂停切换具体方法 */
	togglePlayBtnFun() {
		setTimeoutObj && clearTimeout(setTimeoutObj),
			this.data.videoStatus && (this.data.playBtnVisible ? this.setData({
				playBtnVisible: false
			}) : this.showControlBtn());
	},
	toggleVideoStatus: function () {
		// this.data.videoStatus ? this.player.pause() : this.player.play(), this.setData({
		//   videoStatus: !this.data.videoStatus
		// }),
		setTimeoutObj && clearTimeout(setTimeoutObj),
			this.data.videoStatus && this.showControlBtn();
	},
	showControlBtn: function () {
		var t = this;
		this.setData({
			playBtnVisible: !0
		}, function () {
			setTimeoutObj = setTimeout(function () {
				t.setData({
					playBtnVisible: !1
				});
			}, 2e3);
		});
	},
	/* 分享 */
	toggleShareModal: function () {
		this.setData({
			showShareBool: !this.data.showShareBool,
		});
	},
	// 用户点击显示弹窗
	clickPup: function () {
		let _that = this;
		if (!_that.data.clickShowShops) {
			_that.setData({
				clickShowShops: true,
			})
		}
		if (_that.data.showShopsOpen) {
			_that.setData({
				showShopsOpen: false,
			})
			setTimeout(() => {
				_that.setData({
					clickShowShops: false,
				})
			}, 500)
		} else {
			_that.setData({
				showShopsOpen: true
			})
		}
	},
	/* 获取商品 */
	loadGoods() {
		let par = {
			roomId: this.data.roomId
		}
		App.ajax(url.liveGoodsListUrl, {
			...this.data.shopParams,
			...par
		}, 'GET').then(res => {
			this.data.goodsList = [...this.data.goodsList, ...res.rows]
			this.setData({
				goodsList: this.data.goodsList,
				hasNextPage: res.hasNextPage
			})
		})
	},
	/* 加入购物车 */
	addcart(e) {
		let params = {
			goodsId: e.target.dataset.goodsid,
			number: 1,
			anchorId: this.data.roomInfo.anchorInfo.id,
			roomId: this.data.roomInfo.id
			// skuId: e.target.dataset.skuid
		}
		App.ajax(url.addShopCar, params, 'post').then(res => {
			if (res.code == 0) {
				this.goCart()
			}
		})
	},
	/* 跳转购物车 */
	goCart() {
		wx.navigateTo({
			url: '/pages/cart/index'
		})
	},
	/* 获取直播间详情 */
	getLiveInfo(e) {
		let params = {
			roomId: e,
			// skuId: e.target.dataset.skuid
		}
		wx.showLoading({
			title: "加载中..."
		});
		App.ajax(url.liveDetailUrl, params, 'get').then(res => {
			wx.hideLoading();
			this.setData({
				"roomInfo": res.data,
				"streamInfo": res.data.streamInfo
			})
			this.checkFocusFun();
			this.ctx = wx.createLivePlayerContext('player')
		})
	},
	/* 分享 */
	onShareAppMessage(res) {
		let url_data = "";
		if (wx.getStorageSync('isMember')) {
			url_data = `pages/live/sonpages/player/player?shareUserId=${wx.getStorageSync('userId')}&id=${this.data.roomId}`;
		} else {
			url_data = wx.getStorageSync('shareUserId') != '' ?
				`pages/live/sonpages/player/player?shareUserId=${wx.getStorageSync('shareUserId')}&id=${this.data.roomId}`: `pages/live/sonpages/player/player?id=${this.data.roomId}`;
		}
		return {
			title: this.data.roomInfo.anchorInfo.nickName + '的直播间',
			path: url_data,
			imageUrl: this.data.roomInfo.coverHUrl
		}
	},
	/* 关注，取消关注 */
	focusFun() {
		let params = {
			id: this.data.roomInfo.anchorInfo.id,
			type: 1
		}
		App.ajax(url.focusUrl, params, 'post').then(res => {
			if (res.code == 0) {
				this.setData({
					isFocus: !this.data.isFocus
				})
			}
		})
	},
	/* 检测是否已关注主播 */
	checkFocusFun() {
		let params = {
			id: this.data.roomInfo.anchorInfo.id
		}
		App.ajax(url.checkFocusUrl, params, 'get').then(res => {
			this.setData({
				isFocus: res.data.isFocus
			})
		})
	},
	getQrcode() {
		let shareUserId = null
		if (wx.getStorageSync('isMember')) {
				shareUserId = wx.getStorageSync('userId');
		} else {
				shareUserId = wx.getStorageSync('shareUserId') || '';
		}
		const params = {
			page: 'pages/live/sonpages/player/player',
			scene: `${shareUserId}&${this.data.roomId}`,
			isHyaline: true,
			width: '280'
		}
		App.ajax(url.getQrcode, params, 'post').then(res => {
			this.setData({
				qrcodeImg: res.data
			})
		})
	},
	cancelImgFunc() {
		this.setData({
			maskHidden: false
		})
	},
	creatBanner() {
		var that = this;
		this.setData({
			maskHidden: false,
			showShareBool: false
		});
		wx.showToast({
			title: '图片生成中...',
			icon: 'loading',
			duration: 1000
		});
		setTimeout(function () {
			wx.hideToast()
			that.createNewImg();
			that.setData({
				maskHidden: true
			});
		}, 1000)
	},
	saveImgFunc() {
		wx.saveImageToPhotosAlbum({
			filePath: this.data.imagePath,
			success(res) {}
		})
	},
	createNewImg: function () {
		var that = this;
		var context = wx.createCanvasContext('mycanvas2');
		// 背景
		context.setFillStyle("#fff")
		context.fillRect(0, 0, 500, 650)
		// 主图海报
		var path = this.data.roomInfo.coverHUrl;
		wx.downloadFile({
			url: this.data.roomInfo.coverHUrl,
			success(qrcodeImgOBJ) {
				if (qrcodeImgOBJ.statusCode === 200) {
					context.save()
					context.drawImage(qrcodeImgOBJ.tempFilePath, 20, 100, 360, 360);
					context.draw(true, () => {
						wx.canvasToTempFilePath({
							canvasId: 'mycanvas2',
							success: function (res) {},
						})
					});
				}
			}
		})
		// 绘制名字
		context.setFontSize(20);
		context.setFillStyle('#333333');
		context.fillText(this.data.roomInfo.anchorInfo.nickName, 85, 60);
		context.stroke();
		// 绘制名字
		context.setFontSize(16);
		context.setFillStyle('#999999');
		// context.setTextAlign('center');
		context.fillText('轮到你播', 20, 630);
		context.stroke();
		// 小程序码
		wx.downloadFile({
			url: that.data.qrcodeImg,
			success(qrcodeImgOBJ) {
				if (qrcodeImgOBJ.statusCode === 200) {
					context.save()
					context.drawImage(qrcodeImgOBJ.tempFilePath, 252, 500, 128, 128);
					context.draw(true, () => {
						wx.canvasToTempFilePath({
							canvasId: 'mycanvas2',
							success: function (res) {},
						})
					});
				}
			}
		})
		// 头像
		wx.downloadFile({
			url: this.data.roomInfo.anchorInfo.avatarUrl,
			success(res) {
				if (res.statusCode === 200) {
					context.save()
					context.beginPath()
					context.arc(50, 50, 30, 0, 2 * Math.PI)
					context.clip();
					context.drawImage(res.tempFilePath, 20, 20, 60, 60);
					context.restore()
					context.draw(true, () => {
						wx.canvasToTempFilePath({
							canvasId: 'mycanvas2',
							success: function (res) {},
						})
					});
				}
			}
		})
		context.draw();
		//将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
		setTimeout(function () {
			wx.canvasToTempFilePath({
				canvasId: 'mycanvas2',
				success: function (res) {
					var tempFilePath = res.tempFilePath;
					that.setData({
						imagePath: tempFilePath,
						canvasHidden: true
					});
				},
				fail: function (res) {
					console.log(res);
				}
			});
		}, 2000);
	},
	closeShareFunc() {
		this.setData({
			showShareBool: false
		})
	},
})